package yf.mall.controller.api;

import com.github.pagehelper.PageHelper;
import com.yf.annotation.IgnoreAuth;
import com.yf.annotation.LoginUserId;
import com.yf.response.RRException;
import org.springframework.web.bind.annotation.*;
import yf.mall.dao.*;
import yf.mall.entity.*;
import com.yf.response.R;
import yf.mall.enums.BannerTypeEnum;
import yf.mall.enums.MallActStatusEnum;
import yf.mall.enums.MallGoodsSaleTypeEnum;
import yf.mall.enums.MallTypeTypeEnum;
import yf.mall.service.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@RestController
@RequestMapping("/api/home")
public class ApiHomeController {

    @Autowired
    private BannerService bannerService;

    @Autowired
    private MallGoodsService mallGoodsService;

    @Autowired
    MallActDao mallActDao;
    @Autowired
    ShopService shopService;
    @Autowired
    MallTypeDao mallTypeDao;
    @Autowired
    GoodsQualificationService goodsQualificationService;
    @Autowired
    private LiveService liveService;
    @Autowired
    private CommentService commentService;


    /***
     * 首页所有的数据都从这里来了 根据级别 团队隐藏
     * @return
     */
    @GetMapping("/index")
    public R index(@LoginUserId Long userId){
        //首先是幻灯片
        List<BannerEntity> bannerList = bannerService.findByType(BannerTypeEnum.CENTER.getIndex());
        //售卖类型
        List<SaleTypesEntity> saleTypeList = saleTypesService.findAllAsc();
        //生活精品就是分享有利 找9个
        List<MallGoodsEntity> liveGoodsList = mallGoodsService.findByHome(MallGoodsSaleTypeEnum.RETAIL.getIndex(),0,9);
        liveGoodsList = goodsService.filterByLevel(userId,liveGoodsList);
        //每日优选找9个
        List<MallGoodsEntity> dayGoodsList = mallGoodsService.findByHome(MallGoodsSaleTypeEnum.DAY_SEL.getIndex(),0,9);
        dayGoodsList = goodsService.filterByLevel(userId,dayGoodsList);
        Boolean flag = actService.lotteryAct();
        //找到商城配置
        MallConfigEntity config = configDao.get(1L);
        return R.ok().putExtra("bannerList",bannerList).putExtra("lotteryFlag",flag).putExtra("liveGoodsList",liveGoodsList).putExtra("dayGoodsList",dayGoodsList).putExtra("saleTypeList",saleTypeList).putExtra("config",config);
    }

    @Autowired
    private LotteryActService actService;

    @Autowired
    private MallConfigDao configDao;

    @Autowired
    private MallGoodsService goodsService;

    //分页查找 根据级别 团队隐藏
    @GetMapping("/goods")
    public R goods(@LoginUserId Long userId,Integer saleType,Integer page,Integer size){
        List<MallGoodsEntity> goodsList = mallGoodsService.findByHome(saleType,page,size);
        goodsList = goodsService.filterByLevel(userId,goodsList);
        return R.ok(goodsList);
    }

    //获取售卖类型
    @GetMapping("/saleType")
    public R saleType(){
        //售卖类型
        List<SaleTypesEntity> saleTypeList = saleTypesService.findAllAsc();
        //产品分类
        List<MallTypeEntity> types = mallTypeDao.findByType(MallTypeTypeEnum.TWO.getIndex());
        return R.ok(saleTypeList).putExtra("types",types);
    }

    //获取所有分类
    @GetMapping("/type")
    public R type(){
        List<MallTypeEntity> types = mallTypeDao.findByType(MallTypeTypeEnum.TWO.getIndex());
        return R.ok(types);
    }

    @Autowired
    private SaleTypesService saleTypesService;

    //首页
    @GetMapping({"/banner/{type}", "/banner"})
    @IgnoreAuth
    public R banner(@PathVariable(required = false, name = "type") Integer type) {
        //中部活动图片
        List<BannerEntity> topAct = bannerService.findTopAct();

        Map<String, Object> map = new HashMap<>();
        map.put("link_id", type);
        List<BannerEntity> bannerEntities = bannerService.queryList(map);


        return R.ok(bannerEntities).putExtra("topAct", topAct);
    }

//    //产品 TODO 分页 隐藏字段
//    @GetMapping("/goods")
//    @IgnoreAuth
//    public R goods(int limit,int page) {
//        List<MallGoodsEntity> mallGoodsEntities = mallGoodsService.topList(limit,page);
//        return R.ok(mallGoodsEntities);
//    }

    @Autowired
    private UserDao userDao;

    @Autowired
    private LevelDao levelDao;
    @Autowired
    private SaleTypeInfoService saleTypeInfoService;

    //产品详情 TODO 隐藏字段
    @GetMapping("/goods/info/{id}")
    public R info(@LoginUserId Long userId, @PathVariable("id") Long goodsId,@RequestParam(required = false) Long teamId) {
        MallGoodsEntity mallGoodsEntity = mallGoodsService.getDetail(goodsId);
        LevelEntity levelEntity = levelDao.findByUserId(userId);
        //是否可见
        if(mallGoodsEntity.getLevelName()!=null&&mallGoodsEntity.getLevelName().contains(levelEntity.getName())){
            throw new RRException("级别不够!");
        }
        //从活动获取绑定产品
       // MallActEntity mallActEntity = mallActDao.findByGoodsIdAndstatus(mallGoodsEntity.getId(), MallActStatusEnum.OPEN.getIndex());
        List<MallActEntity> actEntities = mallActDao.findByBindGoodsId(goodsId);
        SaleTypeInfoEntity saleType = saleTypeInfoService.findByGoodsId(goodsId);
        List<MallGoodsEntity> bindList = new ArrayList<>();
        if(actEntities.size() > 0){
            for (MallActEntity mallActEntity : actEntities) {
                if (mallActEntity != null && mallActEntity.getEnd().after(new Date())) {
                    Long actGoodsId = mallActEntity.getGoodsId();
                    //存在绑定产品
                    if (actGoodsId != null) {
                        UserEntity userEntity = userDao.get(userId);
                        levelEntity = levelDao.get(userEntity.getLevelId());
                        MallGoodsEntity bindGoods = mallGoodsService.get(actGoodsId);
                        MallActEntity bindAct = mallActDao.findByGoodsIdAndstatus(actGoodsId, MallActStatusEnum.OPEN.getIndex());
                        // 限制了当前级别
                        if (levelEntity != null &&bindAct!=null&& bindAct.getLevel() != null && bindAct.getLevel().contains(levelEntity.getName())) {
                            bindGoods = null;
                        }
                        if (bindGoods != null) {
                            bindGoods.setBindNumber(mallActEntity.getBindGoodsQuantity());
                            if (mallActEntity.getFirstGoodsQuantity() != null && mallActEntity.getFirstGoodsQuantity() > 0) {
                                bindGoods.setFirstBindNumber(mallActEntity.getFirstGoodsQuantity());
                            }
                        }
                        if (bindGoods != null){
                            bindList.add(bindGoods);
                        }
                    }
                }
            }
        }

        //获取店铺
        ShopEntity shopEntity = null;
        if (mallGoodsEntity.getUserId() != null) {
            shopEntity = shopService.findByUserId(mallGoodsEntity.getUserId());
        }
        //获取类别
        List<Long> typeIds = mallTypeDao.findByGoodsId(goodsId);
        List<String> list = new ArrayList<>();
        if (typeIds != null && typeIds.size() > 0) {
            for (Long typeId : typeIds) {
                MallTypeEntity mallTypeEntity = mallTypeDao.get(typeId);
                if (mallTypeEntity != null) {
                    list.add(mallTypeEntity.getName());
                }
            }
        }
        //获取品牌名
        GoodsQualificationEntity entity = goodsQualificationService.findByGoodsId(goodsId);
        String brandName = null;
        if (entity != null) {
            brandName = entity.getBrandName();
        }
        //获取直播
        Long liveId = null;
        List<Long> lives = liveService.findByGoodsId(mallGoodsEntity.getId());
        if (lives != null && lives.size() > 0) {
            liveId = lives.get(0);
        }
        PageHelper.startPage(0, 2);
        //获取评论信息
        List<CommentEntity> comments = commentService.findByGoodsId(mallGoodsEntity.getId());
        if (comments != null && comments.size() > 0) {
            mallGoodsEntity.setComments(comments);
        }
        //获取团购信息
        GoodsGroupEntity group = groupService.findByUserIdAndGoodsId(userId,goodsId);
        if(group==null&&teamId!=null){
            group = groupService.findByUserIdAndGoodsId(teamId,goodsId);
        }
        return R.ok(mallGoodsEntity).putExtra("bindList", bindList)
                .putExtra("shop", shopEntity).putExtra("typeName", list).putExtra("brandName", brandName)
                .putExtra("liveId", liveId).putExtra("saleType",saleType).putExtra("group",group);
    }

    @Autowired
    private GoodsGroupService groupService;

}

